/**
 * Created by YJH on 2018/5/24.
 */
import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    TouchableOpacity,
    Image,
    ListView,
    DeviceEventEmitter,
    RefreshControl,
} from 'react-native';

import GitHubTrending from 'GitHubTrending';
import NavigationBarComponent from '../NavigationBarComponent';
import ScrollableTabView, {ScrollableTabBar} from 'react-native-scrollable-tab-view';
import DataRespository, {FLAG_STORAGE} from '../../expand/dao/DataRespository';
import LanguageDao, {FLAG_LAN} from '../../expand/dao/LanguageDao';
import RespositoryTrendingCell from '../../common/RespositoryTrendingCell';
import RepositoryDetailPage from '../../page/home/RepositoryDetailPage'
import Popover from '../../module/Popover';
import TimeSpan from '../../module/TimeSpan';
import FavoriteDao from '../../expand/dao/FavoriteDao';
import ProjectModulePopular from '../../module/ProjectModulePopular';
import FavoriteUtil from '../../util/FavoriteUtil';
import {FLAG_TAB} from '../home/HomePage';
import BasePage from '../home/BasePage';
import MoreMenu, {MORE_MENU} from '../../common/MoreMenu';
import GlobalStyles from '../../../res/styles/GlobalStyles';

const TimeSpanArray = [new TimeSpan('今天', 'since=daily'),
    new TimeSpan('本周', 'since=weekly'),
    new TimeSpan('本月', 'since=monthly')];
const URL = 'https://github.com/trending/';
export default class TrendingPage extends BasePage {

    constructor(props) {
        super(props);
        this.LanguageDao = new LanguageDao(FLAG_LAN.flagLanguage);
        this.state = {
            txtFetch: '拉取数据中，请稍后..',
            url: URL,
            dataArray: [],
            titleTxt: '今天',
            isVisible: false,
            buttonRect: {},
            timeSpan: TimeSpanArray[0],
            theme:this.props.hTheme,
        };

        this.gitHubTrending = new GitHubTrending();


    }

    componentWillReceiveProps(nextProps){
        if(nextProps&&nextProps.hTheme&&nextProps.hTheme!==this.props.hTheme){
            this.setState({
                theme:nextProps.hTheme,
            })
        }
    }

    /** view加载完之后就获取存储的标签状态数据 并赋值给 dataArray */
    componentDidMount() {
        super.componentDidMount();
        this.loadDataFromLanguageDao();
    }

    moreMenuClick = () => {
        this.refs.moreMenu.open();
    };

    renderMoreMenu() {
        let params = {...this.props, fromPage: FLAG_TAB.flag_popularTab};
        return <MoreMenu
            ref="moreMenu"
            {...params}
            menus={[MORE_MENU.website, MORE_MENU.custom_theme, MORE_MENU.share]}
            anchorView={() => this.refs.moreMenuButton}/>
    }


    loadDataFromLanguageDao() {
        this.LanguageDao.fetch()
            .then(result => {
                this.setState({
                    dataArray: result,
                });
            }).catch(error => {
            console.log(error);
        })
    }

    showPopover() {
        this.refs.button.measure((ox, oy, width, height, px, py) => {
            this.setState({
                isVisible: true,
                buttonRect: {x: px, y: py, width: width, height: height}
            });
        });
    }

    closePopover() {
        this.setState({isVisible: false});
    }


    titleView() {
        return <View>
            <TouchableOpacity ref='button' onPress={() => this.showPopover()}>
                <View style={{flexDirection: 'row', alignItems: 'center'}}>
                    <Text style={{fontSize: 16, color: 'white'}}>{this.state.titleTxt}</Text>
                    <Image style={{width: 16, height: 16, marginLeft: 5, tintColor: 'white'}}
                           source={require('../../../res/images/ic_tiaozhuan_down.png')}/>
                </View>
            </TouchableOpacity>

        </View>
    }

    onSelectTimeSpan(item) {
        this.setState({
            titleTxt: item.showTxt,
            timeSpan: item,
            isVisible: false,
        })
    }

    /**
     * 功能：右侧的搜索按钮
     * */
    getRightSearchButton() {
        return <TouchableOpacity
            style={{left:GlobalStyles.windowWidth-40}}
            ref='moreMenuButton' onPress={this.moreMenuClick}>
            <Image
                style={{width: 20, height: 20, margin: 5}}
                source={require('../../../res/images/ic_more_vert_white_48pt.png')}
            />
        </TouchableOpacity>
    }

    render() {
        //防止渲染抖动:因为方法render执行在componentDidMount之后，执行到render时由于还是不知道TabPage的数量，无法计算显示渲染长度。
        const tabs = this.state.dataArray.length > 0 ? <ScrollableTabView
            renderTabBar={() => <ScrollableTabBar/>}
            tabBarBackgroundColor={this.state.theme.themeColor}
            tabBarInactiveTextColor='mintcream'
            tabBarActiveTextColor='white'
            tabBarUnderlineStyle={{backgroundColor: 'white', height: 3}}
        >

            {this.state.dataArray.map((result, i, array) => {
                let lan = array[i];
                return lan.checked ?
                    <TabPage key={i} tabLabel={lan.name} hTheme={this.state.theme} timeSpan={this.state.timeSpan}{...this.props}/> : null;
            })}

        </ScrollableTabView> : null;

        let popView = <Popover
            isVisible={this.state.isVisible}
            fromRect={this.state.buttonRect}
            onClose={() => this.closePopover()}
            placement='bottom'
            contentStyle={{backgroundColor: '#343434', opacity: 0.8}}
        >
            <View style={{alignItems: 'center'}}>
                {TimeSpanArray.map((result, i, arr) => {
                    return <TouchableOpacity key={i} onPress={() => this.onSelectTimeSpan(arr[i])}>
                        <Text style={{fontSize: 16, padding: 5, color: 'white'}}>{arr[i].showTxt}</Text>
                    </TouchableOpacity>
                })}
            </View>
        </Popover>;

        return (
            <View style={styles.container}>
                <NavigationBarComponent
                    titleView={this.titleView()}
                    style={this.state.theme.styles.navBar}
                    statusBar={{backgroundColor:this.state.theme.themeColor}}
                    title={'热搜'}
                    rightButton={this.getRightSearchButton()}/>
                {tabs}
                {popView}
                {this.renderMoreMenu()}
            </View>
        )
    }
}


class TabPage extends Component {
    constructor(props) {
        super(props);
        this.dataRespository = new DataRespository(FLAG_STORAGE.flag_trending);
        this.favoriteDao = new FavoriteDao(FLAG_STORAGE.flag_trending);
        this.items = [];
        this.state = ({
            searchKey: this.props.tabLabel,
            result: '页面数据加载中..',
            dataSource: new ListView.DataSource({
                rowHasChanged: (r1, r2) => r1 !== r2
            }),
            isLoading: false,
            favoriteKeys: [],
            theme:this.props.hTheme,
        })
    }


    /** 该方法是在上个组件传值到当前组件过程 回调此方法
     * 由 <TabPage key={i} tabLabel={lan.name} timeSpan={this.state.timeSpan}{...this.props}/>实现
     * 当上个组件中的timeSpan发生变化就会调用下面的方法并将timeSpan传给nextProps
     * */
    componentWillReceiveProps(nextProps) {

        if (nextProps.timeSpan !== this.props.timeSpan) {
            this.onLoad(nextProps.timeSpan, true);
        }

        if (nextProps.hTheme !== this.props.theme) {
            this.setState({
                theme: nextProps.hTheme
            })
        }
    }

    getFavoriteKey() {
        return this.favoriteDao.getFavorKeys()
            .then(keys => {
                if (keys) {
                    this.updateState({favoriteKeys: keys})
                }
                this.flushFavoriteState()
            })
            .catch(e => {
                this.flushFavoriteState();
            })
    }

    /** 更新 project item 的搜藏的状态*/
    flushFavoriteState() {
        let projectModules = [];
        for (let i = 0, l = this.items.length; i < l; i++) {
            projectModules.push(new ProjectModulePopular(this.items[i],
                FavoriteUtil.checkFavorite(this.items[i], this.state.favoriteKeys)))
        }

        this.updateState({
            result: JSON.stringify(projectModules),
            isLoading: false,
            dataSource: this.getDataSource(projectModules),
        });
    }

    getDataSource(projectModules) {
        return this.state.dataSource.cloneWithRows(projectModules);
    }

    updateState(dic) {
        if (!this) return;
        this.setState(dic);
    }

    genUrl(timeSpan) {
        return URL + this.state.searchKey + timeSpan.searchTxt;
    }

    /** 加载网络数据*/
    onLoad(timeSpan, isRefresh) {
        let url = this.genUrl(timeSpan);
        this.setState({
            isLoading: isRefresh,
        });

        this.dataRespository
            .fetchRespository(url)
            .then(result => {
                this.items = result && result.items ? result.items : result ? result : [];
                // this.setState({
                //     result: JSON.stringify(items),
                //     dataSource: this.state.dataSource.cloneWithRows(items),
                //     isLoading: false,
                // });
                this.getFavoriteKey();
                if (!this.items || isRefresh && result && result.update_date && !this.dataRespository.checkData(result.update_date)) {
                    DeviceEventEmitter.emit('showToast', '数据过时..');
                    //过时情况
                    return this.dataRespository.fetNetRespository(url);
                } else {
                    DeviceEventEmitter.emit('showToast', '加载缓存数据..');
                }
            })
            .then(items => {
                if (!items || items.length === 0) return;
                // this.setState({
                //     result: JSON.stringify(items),
                //     dataSource: this.state.dataSource.cloneWithRows(items),
                //     isLoading: false,
                // });
                this.getFavoriteKey();

                DeviceEventEmitter.emit('showToast', '加载网络数据..');
            })
            .catch(error => {
                this.setState({
                    result: JSON.stringify(error)
                })
            })
    }

    componentDidMount() {
        //页面装载之后调用
        this.onLoad(this.props.timeSpan, true);
    }
    componentWillReceiveProps(nextProps) {
        if (nextProps.hTheme !== this.props.theme) {
            this.setState({
                theme: nextProps.hTheme
            })
        }
        this.flushFavoriteState();
    }

    renderSeparator(sectionID, rowID, adjacentRowHighlighted) {
        return <View key={rowID} style={styles.item_line}>
        </View>
    }

    goItemDetail(data) {
        this.props.navigator.push({
            component: RepositoryDetailPage,
            params: {
                projectModule: data,
                isTrending: true,
                theme:this.props.theme,
                ...this.props,//这个是延展属性，而延展属性中会有navigator
            },
        });
    }

    /** 这个是从二级组件回调的方法*/
    onFavoritePressed(item, isFavorite) {
        if (isFavorite)
            this.favoriteDao.savaFavoriteItem(item.fullName, JSON.stringify(item));
        else this.favoriteDao.removeFavoriteItem(item.fullName)
    }

    renderRow(projectModule) {
        return <RespositoryTrendingCell
            key={projectModule.item.fullName}
            goItemDetail={() => {
                this.goItemDetail(projectModule);
            }}
            projectModule={projectModule}
            hTheme={this.state.theme}
            onFavoritePressed={(item, isFavorite) => this.onFavoritePressed(item, isFavorite)}
            {...this.props}
        />
    }

    onLoadRefresh() {
        setTimeout(() => {
            this.onLoad(this.props.timeSpan, true);
        }, 1500);
    }

    render() {
        return <View style={{flex: 1}}>
            <ListView
                dataSource={this.state.dataSource}
                renderRow={(data) => this.renderRow(data)}
                renderSeparator={(sectionID, rowID, adjacentRowHighlighted) => this.renderSeparator(sectionID, rowID, adjacentRowHighlighted)}
                enableEmptySections={true}
                // renderFooter={() => this.renderFooter()}
                refreshControl={
                    <RefreshControl
                        refreshing={this.state.isLoading}
                        onRefresh={() => this.onLoadRefresh()}
                    />}
            />

        </View>
    }

}


const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#FCFCFC',
    },
    newTextStyle: {
        fontSize: 24,
    },
    ViewForTextStyle: {
        height: 60,
        width: 180,
        borderColor: 'green',
        borderWidth: 1,
        borderRadius: 5,
        alignSelf: 'center',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#ddd',
        margin: 5
    },
    searchButton: {
        width: 1,
        height: 1,
        marginLeft: window.width - 60,
    },

    boy_text: {
        fontSize: 18,
        color: 'black',
        alignSelf: 'center',
    },
    tab_image: {
        width: 20,
        height: 20,
    },
    text: {
        fontSize: 18,
        marginTop: 10,
        alignSelf: 'center',
    },
    button: {
        height: 60,
        marginTop: 30,
        fontSize: 20,
        alignSelf: 'center',
    },
    edt: {
        height: 50,
        marginTop: 30,
        minWidth: 300,
        alignSelf: 'center',
        borderColor: '#02F78E',
    },
    item_row: {
        height: 60
    }, item_line: {
        height: 1,
        backgroundColor: '#FCFCFC'
    },
});